/**
 * 个人信息
 */
import React from 'react';
import { InputItem, Toast, DatePicker, Modal } from 'antd-mobile';
import { Spin } from 'antd';
import { router, withRouter } from 'umi';
import moment from 'moment';
import { createForm } from 'rc-form';
import { useRequest, defaultFormatResult } from '@/hooks';
import { PageWrap, EditListItem, ListItem, Button, Picker, Radio } from './components';
import { getRegisterDetail, updatePersonalInfo } from '../service';
import { useFormChange } from '../hooks';
import arrowIcon from '../images/icon-arrow-down.png';
import styles from './Register.less';

const ItemHead = ({ title, content }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ flex: 1, fontSize: 14, color: '#49536c' }}>{title}</div>
        <div style={{ marginLeft: 8 }}>{content}</div>
    </div>
);

const PhoneType = props => (
    <div
        onClick={props.onClick}
        style={{
            flex: 1,
            display: 'flex',
            alignItems: 'center',
            fontSize: 16,
            color: '#2a2f3c'
        }}
    >
        {props.extra}
        <img alt="" src={arrowIcon} style={{ width: 16, height: 16, margin: '0 8px 0 4px' }} />
    </div>
);

const dateToMoment = date => {
    if (date) {
        return moment(date);
    }
    return null;
};

const PersonInfo = ({ location, form }) => {
    const { query } = location;
    const { getFieldProps } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);

    const { hasFormChange, initialForm } = useFormChange(form);
    console.log('getRegisterDetail---------PersonInfo');
    const { loading, data } = useRequest(() => getRegisterDetail(query?.nid), {
        ...defaultFormatResult,
        onSuccess: () => {
            initialForm();
        }
    });

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            // console.log('handleSubmit -> values', values);
            const { phoneAreaCode = [], lastPostStatus = [] } = values;
            // if (!talentName && !talentNameEn) {
            //     Toast.info('请输入姓名信息，中文名、英文名至少输入一个');
            //     return;
            // }
            if (!err) {
                const params = {
                    ...values,
                    phoneAreaCode: phoneAreaCode.length > 0 ? phoneAreaCode[0] : '',
                    lastPostStatus: lastPostStatus.length > 0 ? lastPostStatus[0] : '',
                    talentBirth: dateToMoment(values?.talentBirth)?.format('YYYY-MM-01'),
                    talentStartWorkTime: dateToMoment(values?.talentStartWorkTime)?.format('YYYY-MM-01'),
                    id: data?.id
                };
                // console.log(params);
                // console.log(JSON.stringify(params));
                setSubmitLoading(true);
                updatePersonalInfo(params)
                    .then(res => {
                        const { code, msg } = res;
                        if (code === 10000) {
                            // Toast.info('提交成功');
                            history.goBack();
                        } else {
                            Toast.info(msg);
                        }
                    })
                    .finally(() => {
                        setSubmitLoading(false);
                    });
            } else {
                const tempList = Object.values(err);
                if (tempList && tempList.length > 0) {
                    const { errors } = tempList[0];
                    Toast.info(errors[0]?.message);
                }
            }
        });
    };

    const formatDate = date => {
        const pad = n => (n < 10 ? `0${n}` : n);
        const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}`;
        return `${dateStr}`;
    };

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    return (
        <PageWrap
            title="个人信息"
            navbarProps={{ onLeftClick: handleLeftClick }}
            footer={
                <Button type="primary" loading={submitLoading} onClick={handleSubmit}>
                    保存
                </Button>
            }
        >
            <div style={{ padding: '0 16px' }}>
                <Spin spinning={loading}>
                    <EditListItem title="中文名" showArrow={false}>
                        <InputItem
                            {...getFieldProps('talentName', {
                                initialValue: data?.talentName || '',
                                rules: [{ required: true, message: '请输入中文名' }]
                            })}
                            clear
                            placeholder="请输入"
                        />
                    </EditListItem>
                    <EditListItem title="英文名" showArrow={false} required={false}>
                        <InputItem
                            {...getFieldProps('talentNameEn', {
                                initialValue: data?.talentNameEn || '',
                                rules: [{ required: false, message: '请输入英文名' }]
                            })}
                            clear
                            placeholder="请输入"
                        />
                    </EditListItem>
                    <ListItem
                        showArrow={false}
                        titleStyle={{ padding: '6px 0' }}
                        title={
                            <ItemHead
                                title="性别"
                                content={
                                    <Radio
                                        dataSource={[
                                            { label: '男', value: '1' },
                                            { label: '女', value: '2' }
                                        ]}
                                        {...getFieldProps('talentSex', {
                                            initialValue: data?.talentSex || '1',
                                            rules: [{ required: true, message: '请选择性别' }]
                                        })}
                                    ></Radio>
                                }
                            />
                        }
                    ></ListItem>
                    <EditListItem title="手机号" showArrow={false}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <Picker
                                title="选择国际电话区号"
                                data={[
                                    { label: '+86', value: '86' },
                                    { label: '+65', value: '65' }
                                ]}
                                {...getFieldProps('phoneAreaCode', {
                                    initialValue: [data?.phoneAreaCode || '86']
                                })}
                            >
                                <PhoneType />
                            </Picker>
                            <div style={{ flex: 1, marginLeft: 8 }}>
                                <InputItem
                                    type="phone"
                                    {...getFieldProps('talentPhone', {
                                        initialValue: data?.talentPhone || '',
                                        rules: [{ required: true, message: '请输入手机号' }]
                                    })}
                                    clear
                                    placeholder="请输入"
                                />
                            </div>
                        </div>
                    </EditListItem>
                    <EditListItem title="个人邮箱" showArrow={false}>
                        <InputItem
                            {...getFieldProps('talentEmail', {
                                initialValue: data?.talentEmail || '',
                                rules: [
                                    { required: true, message: '请输入个人邮箱' },
                                    {
                                        message: '请输入正确的个人邮箱',
                                        type: 'email'
                                    }
                                ]
                            })}
                            clear
                            placeholder="请输入"
                        />
                    </EditListItem>
                    <DatePicker
                        className={styles.customPicker}
                        mode="month"
                        title="出生年月"
                        extra="请选择"
                        format={formatDate}
                        minDate={new Date(0, 0, 0)}
                        maxDate={new Date()}
                        locale={{ okText: '确定', dismissText: '取消' }}
                        {...getFieldProps('talentBirth', {
                            initialValue: (data?.talentBirth && moment(data?.talentBirth).toDate()) || null,
                            rules: [{ required: true, message: '请选择出生年月' }]
                        })}
                    >
                        <EditListItem title="出生年月">请选择</EditListItem>
                    </DatePicker>
                    <DatePicker
                        className={styles.customPicker}
                        mode="month"
                        format={formatDate}
                        minDate={new Date(0, 0, 0)}
                        maxDate={new Date()}
                        title="参加工作时间"
                        extra="请选择"
                        locale={{ okText: '确定', dismissText: '取消' }}
                        {...getFieldProps('talentStartWorkTime', {
                            initialValue:
                                (data?.talentStartWorkTime && moment(data?.talentStartWorkTime).toDate()) || null
                        })}
                    >
                        <EditListItem required={false} title="参加工作时间">
                            请选择
                        </EditListItem>
                    </DatePicker>
                    <Picker
                        title="工作状态"
                        data={[
                            { label: '在职', value: 1 },
                            { label: '离职', value: 2 },
                            { label: '应届生', value: 3 }
                        ]}
                        {...getFieldProps('lastPostStatus', {
                            initialValue: data?.lastPostStatus ? [data?.lastPostStatus] : undefined,
                            rules: [{ required: true, message: '请选择工作状态' }]
                        })}
                    >
                        <EditListItem title="工作状态">请选择</EditListItem>
                    </Picker>
                </Spin>
            </div>
        </PageWrap>
    );
};

export default withRouter(createForm()(PersonInfo));
